package com.yager.util;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

public class EmailUtil {

    private String myMail="1021505034@qq.com";
    private String myMailPwd="pvojpbyrhggmbcde";
    private String myMailSMTP="smtp.qq.com";

    public String getAndSendConfirmation(String email){

        Properties prop=new Properties();
        prop.setProperty("mail.transport.protocol","smtp");
        prop.setProperty("mail.smtp.host",myMailSMTP);
        prop.setProperty("mail.smtp.auth","true");

        Session session=Session.getInstance(prop);
//        session.setDebug(true);

        //生成验证码
        String confirmation="";
        Random random=new Random();
        Integer num;
        for(int i=0;i<6;i++){
            num=random.nextInt(10);
            confirmation+=num.toString();
        }
        System.out.println("验证码为："+confirmation);

        MimeMessage message=new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(myMail,"雅阁Yager","utf-8"));
            message.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(email,"雅阁用户","utf-8"));
            message.setSubject("雅阁 找回密码","utf-8");
            message.setContent("您的找回密码验证码为："+confirmation,"text/html;charset=utf-8");
            message.setSentDate(new Date());
            message.saveChanges();
        } catch (Exception e) {
            e.printStackTrace();
        }


        Transport transport= null;
        try {
            transport = session.getTransport();
            transport.connect(myMail,myMailPwd);
            transport.sendMessage(message,message.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return confirmation;

    }

}
